import {useCallback} from 'react'
import { useSearchUIState } from '../../../../../store/hooks/useSearchUIState';
import { useSearchResultPage } from '../../../../../store/hooks/useSearchResultPage';
import { useInbiz } from '../../../../../store/hooks/useInbiz';
import {
  deleteSearchHistoryByModule,
  deleteSingleSearchHistory,
} from '../../../../../designer/service';
export enum HistoryDeleteTypeEnum {
  /** 全部 */
  ALL,
  /** 单个 */
  SINGLE,
}

export const useDeleteHistory = (
  refresh: () => void,
  setHistoryData: React.Dispatch<React.SetStateAction<any[]>>,
  historyData: any[]
) => {
  const searchResultPage = useSearchResultPage();
  const inbiz = useInbiz()
  const clearStorage = () => {
    let pageId = ''
    if (searchResultPage.searchResultPage) {
      const resultPages = searchResultPage.searchResultPage.split(',')
      pageId = resultPages[0];
    } else {
      pageId = 'page/' + inbiz.pageId
    }

    window.localStorage.removeItem('_searchEngineStatus');
    window.sessionStorage.removeItem('_searchEngineStatus');
  }

  return useCallback(
    async (type: HistoryDeleteTypeEnum, keyWord?: string) => {
      if (type === HistoryDeleteTypeEnum.ALL) {
        // 删除全部
        setHistoryData([]);
        clearStorage()
        await deleteSearchHistoryByModule().then(
          (res: { Code: number }) => {
            if (res.Code == 0) {
              // refresh();
            }
          },
        );
      } else if (keyWord) {
        // 单个历史记录删除
        setHistoryData((prev) => {
          return prev.filter((item) => item !== keyWord);
        });
        await deleteSingleSearchHistory(keyWord).then((res: { Code: number }) => {
          if (res.Code == 0) {
            // onchange()
          }
        });
        if (historyData.length == 0) {
          clearStorage()
        }
      }
    },
    [refresh, setHistoryData],
  );
};
